<?php

require_once 'Core/Db/Table/Abstract.php';
require_once 'Core/Db/Table/Row/Abstract.php';
require_once 'Core/Db/Table/Rowset/Abstract.php';

class Nld_Models_Acl_DbTable extends Core_Db_Table_Abstract
{
	public function init()
	{
		$this->_name 						= 'acl';
		$this->_primary 				= 'taskcode';
		$this->_rowClass 				= 'Core_Db_Table_Row_Abstract';
		$this->_rowsetClass 		= 'Core_Db_Table_Rowset_Abstract';
		
		$this->_dependentTables = array(
			'Acl' 		=> Nld_Models::getTableClass('Acl'),
			'ToUsers' => Nld_Models::getTableClass('Acl/ToUsers'),
			'ToGroup' => Nld_Models::getTableClass('Acl/ToGroup'),
		);

		$this->_referenceMap    = array(
			array(
				'columns'           => 'parentcode',
				'refTableClass'     => Nld_Models::getTableClass('Acl'),
				'refColumns'        => 'taskcode',
			),
			array(
				'columns'           => 'taskcode',
				'refTableClass'     => Nld_Models::getTableClass('Acl/ToUsers'),
				'refColumns'        => 'taskcode',
			),
			array(
				'columns'           => 'taskcode',
				'refTableClass'     => Nld_Models::getTableClass('Acl/ToGroup'),
				'refColumns'        => 'taskcode',
			),
		);
	}
	public function getPermission($index = null)
  {
		$list = array('allow' => 'Cho phép truy cập', 'deny' => 'Cấm truy cập');
    return ($index === null)?$list:@$list[$index];
  }
	public function fetchChild($where = '`parentcode` is null', 
		$whereex = null, $order = null, $level = 0)
	{
    $entries  = array();
    foreach($this->fetchAll(
			($whereex === null)?$where:$where.' AND '.$whereex, 
			($order === null)?array('order asc', 'id asc'):$order) as $entry)
		{
			$entries = array_merge(
									 $entries, 
									 array($entry->toArray()+array('_level' => $level)), 
									 $this->fetchChild('`parentcode` = "'.$entry->taskcode.'"', $whereex, $order)
									 			->toArray());
		}
		return $this->getRowSet($entries);
	}
}